﻿var selectedRowId = { Id: '-1' };
var urlVars;
var ischeckingName = false;

// This method defines column header in grid
function GetColumnNames() {
    return ['', 'Id', 'Điện Thoại', 'Tên Khách Hàng', 'Địa Chỉ', 'Ghi chú',
        //'SP đã mua',
        'Miền', 'Cập nhật sau cùng'];
}

// This methods defines layout/sort/format/etc of column gird
function GetColumnModel() {
    return [{
        name: 'checkbox', index: 'checkbox', width: 20, align: "center", editable: true, edittype: "checkbox",
        formatter: 'checkbox', formatoptions: { disabled: false }, sortable: false
    },
        { name: 'Id', index: 'Id', width: 70, hidden: true },
        { name: 'Phone', index: 'Phone', width: 100, align: "left", sortable: true },
        { name: 'CustomerName', index: 'CustomerName', width: 200, align: "left", sortable: true },
        { name: 'Address', index: 'Address', width: 190, align: "left", sortable: true },
        { name: 'Notes', index: 'Notes', width: 200, align: "left", sortable: true },
        //{ name: 'Bank', index: 'Bank', width: 100, align: "left", sortable: true },
        //{ name: 'CreditCardNumber', index: 'CreditCardNumber', width: 100, align: "left", sortable: true },
        //{ name: 'Products', index: 'Products', width: 250, align: "left", sortable: true },
        { name: 'CustomerRegion', index: 'CustomerRegion', width: 60, align: "center", sortable: true },
        { name: 'LastModified', index: 'LastModified', width: 120, align: "right", sortable: true },
    ];

}


$(document).ready(function () {
    GetCurrentLoginUser(function (data) {
        SetupGrid('#list', "/Home/GetCustomerList", GetColumnNames, GetColumnModel, '#listPager',
        'Name', 'text', 'asc', selectedRowId, GetPostData($("#list"), data.IsAdmin), 360, 893, grid_LoadCompleted);
        $("#list").jqGrid('setGridParam', { datatype: 'json' });

    });

    registerEventHandles();
  

});


function newCustomer() {
    GetCurrentLoginUser(function (data) {
        if (!data || !data.Username || data.Username === '')
            window.location.href = '/User/Login';
        if (!data.IsAdmin) {
            window.location.href = '/User/Login';
        }
        $.blockUI();
        $.ajax({
            url: "/Customer/New",
            data: {},
            contentType: 'text/html',
            dataType: "html",
            type: "get",
            success: function (data) {
                $("#editWindow .modal-body").html(data);
                $('#editWindow .modal-title').html("Thêm Khách Hàng");
                $('#editWindow').modal({ backdrop: false });

                $("#editWindow .modal-dialog").css({ width: 850 });

                $.unblockUI();
            },
            error: function (data) {
                alert("Yêu cầu đăng nhập lại");
                $.unblockUI();
            }
        });

    });

}


function editCustomer() {
    var selectedItems = getSelectedRows();
    if (selectedItems.length == 0)
        return;
    var ajaxUrl = "/Customer/Edit/" + selectedItems[0];

    GetCurrentLoginUser(function (data) {
        if (!data || !data.Username || data.Username === '')
            window.location.href = '/User/Login';

        $.blockUI();
        $.ajax({
            url: ajaxUrl,
            data: {},
            contentType: 'text/html',
            dataType: "html",
            type: "get",
            success: function (data) {
                $("#editWindow .modal-body").html(data);
                $('#editWindow .modal-title').html("Sửa Khách Hàng");
                $('#editWindow').modal({ backdrop: false });
                $("#editWindow .modal-dialog").css({ width: 850 });
                $.unblockUI();
            },
            error: function (data) {
                alert("Yêu cầu đăng nhập lại");
                $.unblockUI();
            }
        });

    });
}



function registerEventHandles() {
    $("#drRegion").change(function () {
        GetCurrentLoginUser(function (user) {
            Search(user.IsAdmin);
        });
    });

    $("#drCategory").change(function () {
        GetCurrentLoginUser(function (user) {
            Search(user.IsAdmin);
        });
    });

    $("#btnSearch").click(function () {
        GetCurrentLoginUser(function (user) {
            Search(user.IsAdmin);
        });
    });

    $("#txtPhone").change(function () {
        GetCurrentLoginUser(function (user) {
            Search(user.IsAdmin);
        });
    });

    $("#btnEdit").click(function () {
        editCustomer();
    });

    $("#btnDel").click(function () {
        var selectedItems = getSelectedRows();
        if (selectedItems.length == 0) return;
        $("#dialog-confirm").dialog({
            resizable: false,
            height: 160,
            modal: true,
            buttons: {
                "Xóa đi": function () {
                    DoDelete();
                    $(this).dialog("close");
                },
                "Khoan đã": function () {
                    $(this).dialog("close");
                }
            }
        });
        function DoDelete() {
            $.blockUI();
            $.ajax({
                url: "/Customer/Delete",
                data: JSON.stringify({ deletedIds: selectedItems }),
                contentType: 'application/json',
                dataType: "json",
                type: "POST",
                success: function (data) {
                    $.unblockUI();
                    $("#list").jqGrid('setGridParam', { datatype: 'json' });
                    $('#list').trigger('reloadGrid');
                    if (data.Success) {
                        showMessage("#alertbox", "Đã xóa khách hàng");
                    }
                    else {
                        showMessage("#alertbox", "Không thể xóa khách hàng!", true);
                    }
                },
                error: function (err) {
                    $.unblockUI();
                    showMessage("#alertbox", "Không thể xóa khách hàng!", true);
                }
            });
        }
    });
}

function grid_LoadCompleted() {
    handleCheckbox();
    handleControls(0);
}
function handleCheckbox() {
    $("#list input[type='checkbox']").change(function () {
        var selectedItems = getSelectedRows();
        handleControls(selectedItems.length);
    });


}

function handleControls(itemSelectedCount) {
    if (itemSelectedCount > 0) {
        $("#btnDel").removeAttr("disabled");
    }
    else {
        $("#btnDel").attr("disabled", true);
    }
    if (itemSelectedCount != 1) {
        $("#btnEdit").attr("disabled", true);
    }
    else {
        $("#btnEdit").removeAttr("disabled");
    }

}

function getSelectedRows() {
    var elements = $("#list input[type='checkbox']:checked").parent().parent();
    var selectedIds = [];

    elements.each(function (e) {
        var id = $(this).attr("id");
        selectedIds.push(id);
    });
    return selectedIds;
}

function Search(isAdmin) {
    GetCurrentLoginUser(function (data) {
        if (!data || !data.Username || data.Username === '')
            window.location.href = '/User/Login';

        $.blockUI();

        $.ajax({
            url: "/Home/GetCustomerList",
            data: GetPostData($("#list"), isAdmin),
            dataType: "json",
            type: "get",
            asyn: false,
            success: function (data) {
                $.unblockUI();
                $('#list').trigger('reloadGrid');
            },
            error: function (err) {
                $.unblockUI();
                //HandleError(err, "Error when searching Customer Name.", "");
                alert('Error occurred when searching customer');
            }
        });
        $("#list").jqGrid('setGridParam', { datatype: 'json' });
    });
}

function GetPostData(list, isAdmin) {

    return {
        sortName: function () { return $(list).jqGrid('getGridParam', 'sortname'); },
        sortOrder: function () {
            return ($(list).jqGrid('getGridParam', 'sortorder'));
        },
        rowId: selectedRowId.Id,
        regionId: function () { return $("#drRegion option:selected").val(); },
        productCategoryId: function () { return $("#drCategory option:selected").val(); },
        phone: function () { return $("#txtPhone").val(); },
        isAdmin: function () { return isAdmin; }
    };
}



//========================================================
function GetCurrentLoginUser(callback) {
    $.ajax({
        url: "/User/GetCurrentLoginUser",
        data: {},
        contentType: 'application/json',
        dataType: "json",
        type: "get",
        success: function (data) {
            callback(data);
        }
    });
}